$(document).ready(function() {
    // 检查认证状态
    if (!utils.checkAuth()) return;
    
    // 显示用户信息
    const userInfo = JSON.parse(localStorage.getItem(STORAGE_KEYS.USER_INFO));
    $('#userName').text(`${userInfo.name}（教师）`);
    
    // 加载统计数据
    loadTeacherStatistics();
    
    // 加载课程列表
    loadTeacherClasses();
});

// 已存的图表实例
let scoreChartInstance = null;

// 获取课程名称（兼容不同的字段名）
function getCourseName(course) {
    // 尝试各种可能的字段名
    return course.ClassName || course.CourseName || course.courseName || course.Name || course.name || '未知课程';
}

// 加载统计数据
function loadTeacherStatistics() {
    $.ajax({
        url: getFullApiPath(ROLE_API_PATHS[2], '/statistics'),
        type: 'GET',
        headers: utils.getAuthHeader(),
        success: function(response) {
            const result = utils.handleApiResponse(response);
            const stats = result.data?.overall_stats || {};
            const distribution = result.data?.score_distribution || {};
            
            $('#totalClasses').text(stats.TotalClasses || 0);
            $('#totalEvaluations').text(stats.TotalEvaluations || 0);
            $('#averageScore').text(
                stats.OverallAverageScore ? parseFloat(stats.OverallAverageScore).toFixed(1) : '暂无'
            );
            
            // 评分分布图表
            updateScoreChart(distribution);
        },
        error: function(xhr) {
            const errorMessage = utils.handleApiError(xhr, '加载统计数据失败');
            utils.showMessage($('#statisticsMessage'), errorMessage, 'danger');
        }
    });
}

// 加载课程列表
function loadTeacherClasses() {
    $.ajax({
        url: getFullApiPath(ROLE_API_PATHS[2], '/classes'),
        type: 'GET',
        headers: utils.getAuthHeader(),
        success: function(response) {
            const result = utils.handleApiResponse(response);
            const courses = result.data || [];
            const $classList = $('#classList');
            $classList.empty();
            
            if (!Array.isArray(courses) || !courses.length) {
                $classList.append('<tr><td colspan="8" class="text-center">暂无课程数据</td></tr>');
                return;
            }
            
            courses.forEach(function(course) {
                const avgScore = course.AverageScore ? parseFloat(course.AverageScore).toFixed(1) : '暂无';
                
                $classList.append(`
                    <tr>
                        <td>${course.ClassID}</td>
                        <td>${course.CourseName}</td>
                        <td>${course.Semester}</td>
                        <td>${course.TimeLocation}</td>
                        <td>${course.StudentCount || 0}</td>
                        <td>${course.EvaluationCount || 0}</td>
                        <td>
                            <div class="rating">
                                ${'★'.repeat(Math.round(course.AverageScore || 0))}${'☆'.repeat(5 - Math.round(course.AverageScore || 0))}
                            </div>
                            ${avgScore}
                        </td>
                        <td>
                            <button class="btn btn-sm btn-primary" onclick="viewClassEvaluations(${course.ClassID}, '${course.CourseName}')">
                                查看评价
                            </button>
                        </td>
                    </tr>
                `);
            });
        },
        error: function(xhr) {
            const errorMessage = utils.handleApiError(xhr, '加载课程列表失败');
            utils.showMessage($('#classMessage'), errorMessage, 'danger');
        }
    });
}

// 显示课程评价
function viewClassEvaluations(classId, courseName) {
    $('#evaluationModalTitle').text(`${courseName} - 评价详情`);
    
    $.ajax({
        url: getFullApiPath(ROLE_API_PATHS[2], `/class/${classId}/evaluations`),
        type: 'GET',
        headers: utils.getAuthHeader(),
        success: function(response) {
            const result = utils.handleApiResponse(response);
            const evaluations = result.data || [];
            const $evaluationList = $('#evaluationList');
            $evaluationList.empty();
            
            if (!Array.isArray(evaluations) || !evaluations.length) {
                $evaluationList.append('<tr><td colspan="5" class="text-center">暂无评价数据</td></tr>');
                return;
            }
            
            evaluations.forEach(function(evaluation) {
                const score = parseInt(evaluation.Score) || 0;
                const stars = '★'.repeat(score) + '☆'.repeat(5-score);
                
                $evaluationList.append(`
                    <tr>
                        <td>${evaluation.StudentID}</td>
                        <td>${evaluation.StudentName}</td>
                        <td><div class="rating">${stars}</div></td>
                        <td>${evaluation.Comment || '无评价内容'}</td>
                        <td>${utils.formatDate(evaluation.EvaluationTime)}</td>
                    </tr>
                `);
            });
            
            const modal = new bootstrap.Modal(document.getElementById('evaluationModal'));
            modal.show();
        },
        error: function(xhr) {
            const errorMessage = utils.handleApiError(xhr, '加载评价详情失败');
            utils.showMessage($('#classMessage'), errorMessage, 'danger');
        }
    });
}

function updateScoreChart(distribution) {
    const data = [
        distribution.Score5Count || 0,
        distribution.Score4Count || 0,
        distribution.Score3Count || 0,
        distribution.Score2Count || 0,
        distribution.Score1Count || 0
    ];
    
    const canvas = document.getElementById('scoreChart');
    if (!canvas) {
        console.error('找不到评分图表canvas元素');
        return;
    }
    
    const ctx = canvas.getContext('2d');
    
    // 如果已存在图表实例，先销毁
    if (scoreChartInstance) {
        scoreChartInstance.destroy();
    }
    
    scoreChartInstance = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: ['5分', '4分', '3分', '2分', '1分'],
            datasets: [{
                label: '评分数量',
                data: data,
                backgroundColor: [
                    '#28a745',
                    '#6f42c1', 
                    '#ffc107',
                    '#fd7e14',
                    '#dc3545'
                ]
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        stepSize: 1
                    }
                }
            }
        }
    });
} 